package com.nwpu.am.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.nwpu.am.constant.properties.SnowflakeProperties;
import com.nwpu.am.mapper.OrderMapper;
import com.nwpu.am.pojo.dto.OrderCreateDTO;
import com.nwpu.am.pojo.dto.page.OrderPageDTO;
import com.nwpu.am.pojo.entity.Order;
import com.nwpu.am.pojo.entity.User;
import com.nwpu.am.result.PageResult;
import com.nwpu.am.service.OrderService;
import com.nwpu.am.utils.id_generator.IdGenerator;

import com.nwpu.am.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    OrderMapper orderMapper;

    @Resource
    private SnowflakeProperties snowflakeProperties;
    @Resource
    private IdGenerator idGenerator;
    public void createOrder(OrderCreateDTO orderCreateDTO) {
        User user = ThreadLocalUtil.get();
        long userId = user.getUserId();

        long orderId = idGenerator.nextId();

        Order order=new Order(orderId, userId,(short)0, orderCreateDTO.getPayMoney(), LocalDateTime.now(),null , orderCreateDTO.getDescription(), orderCreateDTO.getOwnerName(), orderCreateDTO.getOwnerTel());
        orderMapper.insertOrder(order);
    }


    @Override
    public ArrayList<Order> display() {
        return orderMapper.selectAll();
    }

    @Override
    public void updateOrder(OrderCreateDTO orderCreateDTO,Long orderId) {



        orderMapper.updateOrder(orderId, orderCreateDTO.getPayMoney(),orderCreateDTO.getDescription(), orderCreateDTO.getOwnerName(), orderCreateDTO.getOwnerTel());

    }

    @Override
    public void orderFinished(Long orderId) {
        LocalDateTime completeTime=LocalDateTime.now();
        orderMapper.orderFinished(orderId,completeTime, (short) 1);
    }

    @Override
    public Order findById(Long orderId) {
        return orderMapper.selectOrderById(orderId);
    }

    @Override
    public void deleteOrder(Long orderId) {

        orderMapper.deleteOrderById(orderId);
    }

    @Override
    public PageResult<Order> pageQuery(OrderPageDTO orderPageDTO) {
        // 开启分页插件
        PageMethod.startPage(orderPageDTO.getPage(), orderPageDTO.getPageSize());

        // 调用分页方法
        Page<Order> page = orderMapper.pageQuery(orderPageDTO);

        long total = page.getTotal();
        List<Order> result = page.getResult();

        return new PageResult<>(total, result);
    }
}
